package com.botarena.client.admin;

import com.botarena.client.ui.ErrorDialogBox;
import com.botarena.client.ui.GenericDialogBox;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class ResetDatabaseForm extends FormPanel {

	
	ResetDatabaseForm(Label status) {
		HorizontalPanel panel = new HorizontalPanel();

		setAction("/admin/servlet/http/resetDatabase");
		setEncoding(FormPanel.ENCODING_URLENCODED);
		setMethod(FormPanel.METHOD_POST);
		setWidget(panel);
		
		Button reset = createResetButton(status);
		panel.add(reset);
	}

	private Button createResetButton(final Label status) {
		Button reset = new Button("reset database", new ClickHandler() {
			public void onClick(ClickEvent event) {
				submit();
			}
		});
		
		addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
			public void onSubmitComplete(SubmitCompleteEvent event) {
				String result = event.getResults();
				
				try {
					int deleted = Integer.parseInt(result.trim());
					if (deleted > 0) {
						status.setText("deleted " + deleted + "... " + Random.nextInt());
						//submit(); // autousuwanie....
					} else {
						status.setText("Database successfully reset");
					}
					
				} catch (NumberFormatException e) {
					GenericDialogBox dialog = new ErrorDialogBox("Reset database");
					dialog.setMessage(result + " >> " + e);
					dialog.center();
				}
			}
		});	
		
		return reset;
	}
}
